package main

import (
	"compress/gzip"
	"crypto/tls"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"github.com/crozz-net/jsondef/def"
	"log"
	"net/http"
	"os"
	"strings"
)

var (
	pname     = flag.String("name", "", "name of root")
	printType = flag.String("t", "go", "type to print. one of [go, java]")
)

func main() {
	flag.Parse()
	filename := flag.Arg(0)
	name := *pname

	var err error
	var data []byte

	if filename != "" {
		if strings.HasPrefix(filename, "http://") || strings.HasPrefix(filename, "https://")  {
			data, err = sendRequest(filename)
		} else {
			data, err = ioutil.ReadFile(filename)
			if name == "" {
				name = strings.Split(filename, ".")[0]
			}
		}
	} else {
		data, err = ioutil.ReadAll(os.Stdin)
	}
	if err != nil {
		log.Fatal(err)
	}
	if name == "" {
		name = "REPLACE_ME"
	}
	switch *printType {
	case "go":
		def.GoDef(data, name)
	case "java":
		def.JavaDef(data, name)
	default:
		fmt.Println("error type! one of [go, java]")
	}
}

func sendRequest(uri string) ([]byte, error) {
	request, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return nil, err
	}
	request.Header.Add("Accept-Encoding", "gzip, deflate, sdch")
	client := &http.Client{}
	if request.URL.Scheme == "https" {
		client.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	}
	resp, err := client.Do(request)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	if resp.StatusCode == 200 {
		if "gzip" == resp.Header.Get("Content-Encoding") {
			if reader, err := gzip.NewReader(resp.Body); err == nil {
				defer reader.Close()
				return ioutil.ReadAll(reader)
			}
		}
		return ioutil.ReadAll(resp.Body)
	}
	bs, _ := ioutil.ReadAll(resp.Body)
	return bs, errors.New(resp.Status)
}
